from typing import Union

from mg_app_framework import TaskKey, get_handler, get_organization
from motor.core import AgnosticClient, AgnosticCollection, AgnosticDatabase
from pymongo.collection import Collection


def get_mongo_handler(task_name=TaskKey.idi_server) -> AgnosticClient:
    mongo_handler = get_handler(task_name)
    if not mongo_handler:
        raise AttributeError(
            "get_mongo_handler with TaskKey.idi_server fail, mongo_handler is empty!"
        )
    return mongo_handler


def get_mongo_database(db_name: str, task_name=TaskKey.idi_server) -> AgnosticDatabase:
    return get_mongo_handler(task_name).get_database(db_name)


def get_mongo_collection(
        *, collection_name: str, database_name: str = None, task_name=TaskKey.idi_server
) -> Union[Collection, AgnosticCollection]:
    if database_name is None:
        database_name = "idi_{}".format(get_organization())
    return get_mongo_database(database_name, task_name).get_collection(collection_name)


def get_retrospect_collection() -> Union[Collection, AgnosticCollection]:
    collection = get_mongo_collection(
        database_name=f"{get_organization()}_order_retrospect",
        collection_name="work_order_retrospect_records",
    )
    return collection


def get_batch_code_config_collection() -> Union[Collection, AgnosticCollection]:
    """
    原材料批次码与物料信息、可用数量、投料状态等维护在此表
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="production_materials"
    )
    return collection


def get_feeding_config_collection():
    """
    原材料批次码与投料数量、物料编码、投料设备、投料时间等维护在此表
    :return:
    """
    input_raw_collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc",
        collection_name=f"input_raw_record",
    )
    return input_raw_collection


def get_code_generation_collection():
    """
    存放分切极卷码生成条码和传入的所有原料条码的绑定关系
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="code_generation_record"
    )
    return collection


def get_rule_code_collection():
    """
    存放蓝胶码.正负极电芯码生成的绑定关系
    :return:
    """
    """
    字段:
    wip_type: int  # 0,1,2,请求的在制品条码类型
    code: str  # 生成码
    serial_no: str  # 流水号:6位
    create_time: datetime = datetime.now() # 创建时间
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="rule_code_record"
    )
    return collection


def get_new_batch_code_config_collection() -> Union[Collection, AgnosticCollection]:
    """
    IF033完工出站后，将产出信息写入此表，模拟原材料批次码导入功能，
    这张表的作用类似原材料批次码导入表，为不能通过原材料批次码表导入的码值提供便捷校验以及投料操作
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="production_materials_similar"
    )
    return collection


def get_container_status_collection() -> Union[Collection, AgnosticCollection]:
    """
    托盘容器当前状态表
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="container_status"
    )
    return collection


def get_container_mark_config_collection() -> Union[Collection, AgnosticCollection]:
    """容器码规则定义"""
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="container_mark_config"
    )
    return collection


def get_prod_result_param_collection() -> Union[Collection, AgnosticCollection]:
    """
    033、034、035、036、037、038接口的码值与param-list及基础参数组建一条或多条记录，并写入这张表；
    :return:
    """
    """
    {
        "call_id" : "JQ01058",
        "trace_id" : "8941d16b-0581-4e68-8940-a651afff4282",
        "upperpc_code" : "UP1001",
        "user_code" : "Y001",
        "equip_code" : "XES-J21-PESM01",
        "process_code" : "C60-1",
        "wip_no" : "C1",
        "param_list" : [
            {
                "param_code" : "PM001",
                "param_value" : "5.54"
            },
            {
                "param_code" : "PM002",
                "param_value" : "0.98"
            }
        ],
        "time" : "2024-09-30 12:15:30",
        "data_source": "033"
    }
    """
    collection = get_mongo_collection(
        database_name=f"idi_{get_organization()}_upper_pc", collection_name="prod_result_param"
    )
    return collection


def get_basic_config() -> Union[Collection, AgnosticCollection]:
    """
    NG代码定义表
    :return:
    """
    """
    {"index" : NumberInt(1),
    "unqualified_source" : "手动导入",
    "process_code" : "C60-1",
    "process_name" : "正极二次分切",
    "unqualified_product_code" : "C60-1-1",
    "unqualified_product_name" : "A",
    "description" : null}
    """
    collection = get_mongo_collection(
        database_name=f"{get_organization()}_unqualified_product_control", collection_name="basic_config"
    )
    return collection


def get_unqualified_records_backup():
    """
    此表存放的是经由033--037接口生成的不合格品记录，仅作为一张备份表用于辅助定位问题，没有其他用途
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"{get_organization()}_mes",
        collection_name=f"unqualified_records_backup",
    )
    return collection


def get_unqualified_collection():
    """
    获取不合格品记录表
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"{get_organization()}_unqualified_product_control", collection_name="unqualified_records"
    )
    return collection


def get_routing_process_info() -> Union[Collection, AgnosticCollection]:
    """
    获取工艺路线映射表
    :return:
    """
    collection = get_mongo_collection(database_name=f"{get_organization()}_config",
                                      collection_name="production_config_mgm_routing_process_info")
    return collection
